using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WindowsLive.Writer.BlogClient;
using WindowsLive.Writer.CoreServices;

namespace Clarius.WindowsLive.Writer.CrossPostPlugin
{
	public partial class EditOptionsForm : Form
	{
		public static readonly string TargetBlogIdOption = typeof(CrossPost).FullName + "_TargetBlogId";
		public static readonly string PostSummaryOption = typeof(CrossPost).FullName + "_PostSummary";
		public static readonly string PreviewPostOption = typeof(CrossPost).FullName + "_PreviewPost";
		public static readonly string SummaryCharactersOption = typeof(CrossPost).FullName + "_SummaryCharacters";

		public EditOptionsForm()
		{
			InitializeComponent();
		}

		private void EditOptionsForm_Load(object sender, EventArgs e)
		{
			chkSummary.Checked = ApplicationEnvironment.UserSettingsRoot.GetBoolean(
				EditOptionsForm.PostSummaryOption, true);
			chkPreview.Checked = ApplicationEnvironment.UserSettingsRoot.GetBoolean(
				EditOptionsForm.PreviewPostOption, true);
			txtCharacters.Text = ApplicationEnvironment.UserSettingsRoot.GetInt32(
				EditOptionsForm.SummaryCharactersOption, 200).ToString();

			BlogDescriptor[] allBlogs = BlogSettings.GetBlogs(true);
			string targetId =
				ApplicationEnvironment.UserSettingsRoot.GetString(
					TargetBlogIdOption, allBlogs[0].Id);

			foreach (BlogDescriptor desc in allBlogs)
			{
				int idx = cbBlogs.Items.Add(new Blog(desc.Id, desc.Name));
				if (desc.Id == targetId)
					cbBlogs.SelectedIndex = idx;
			}
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			if (DialogResult == DialogResult.OK)
			{
				ApplicationEnvironment.UserSettingsRoot.SetString(
					TargetBlogIdOption, ((Blog)cbBlogs.SelectedItem).Id);
				ApplicationEnvironment.UserSettingsRoot.SetBoolean(
					PostSummaryOption, chkSummary.Checked);
				ApplicationEnvironment.UserSettingsRoot.SetBoolean(
					PreviewPostOption, chkPreview.Checked);
				ApplicationEnvironment.UserSettingsRoot.SetInt32(
					SummaryCharactersOption, Int32.Parse(txtCharacters.Text));
			}
			base.OnClosing(e);
		}

		private void chkSummary_CheckedChanged(object sender, EventArgs e)
		{
			txtCharacters.Enabled = chkSummary.Checked;
			if (chkSummary.Checked)
				txtCharacters.Focus();
		}


		struct Blog
		{
			public string Id;
			public string Name;
			public Blog(string id, string name)
			{
				this.Id = id;
				this.Name = name;
			}

			public override string ToString()
			{
				return Name;
			}
		}

		private void txtCharacters_Validating(object sender, CancelEventArgs e)
		{
			int value;
			e.Cancel = !Int32.TryParse(txtCharacters.Text, out value); 
		}
	}
}